from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_kylin.entity.vo.future_strategy_instance_vo import (
    FutureStrategyInstancePageQueryModel,
    FutureStrategyInstanceModel,
    DeleteFutureStrategyInstanceModel,
)
from module_kylin.service.future_strategy_instance_service import FutureStrategyInstanceService
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

futureStrategyInstanceController = APIRouter(
    prefix='/kylin/futureStrategyInstance',
    tags=['期货策略实例管理'],
    dependencies=[Depends(LoginService.get_current_user)]
)


@futureStrategyInstanceController.get('/list', response_model=PageResponseModel,
                                      dependencies=[
                                          Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:list'))])
async def get_future_strategy_instance_list(
        request: Request,
        instance_page_query: FutureStrategyInstancePageQueryModel = Depends(
            FutureStrategyInstancePageQueryModel.as_query),
        query_db: AsyncSession = Depends(get_db),
):
    """
    获取策略实例列表
    """
    # 获取分页数据
    instance_page_query_result = await FutureStrategyInstanceService.get_strategy_instance_list_services(
        query_db, instance_page_query
    )
    logger.info('获取期货策略实例列表成功')
    return ResponseUtil.success(data=instance_page_query_result)


@futureStrategyInstanceController.get('/{instance_id}', response_model=FutureStrategyInstanceModel,
                                      dependencies=[
                                          Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:query'))])
async def query_detail_future_strategy_instance(request: Request, instance_id: int,
                                                query_db: AsyncSession = Depends(get_db)):
    """
    获取策略实例详情
    """
    instance_detail_result = await FutureStrategyInstanceService.get_strategy_instance_detail_services(
        query_db, instance_id
    )
    logger.info(f'获取策略实例{instance_id}的信息成功')

    return ResponseUtil.success(data=instance_detail_result)


@futureStrategyInstanceController.post('', dependencies=[
    Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:add'))])
@Log(title='期货策略实例管理', business_type=BusinessType.INSERT)
async def add_future_strategy_instance(
        request: Request,
        instance: FutureStrategyInstanceModel,
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
        query_db: AsyncSession = Depends(get_db),
):
    """
    新增策略实例
    """
    add_instance_result = await FutureStrategyInstanceService.add_strategy_instance_services(
        query_db, instance
    )
    logger.info(f'用户{current_user.user.user_name}新增期货策略实例成功')

    return ResponseUtil.success(msg=add_instance_result.message)


@futureStrategyInstanceController.put('', dependencies=[
    Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:edit'))])
@Log(title='期货策略实例管理', business_type=BusinessType.UPDATE)
async def update_future_strategy_instance(
        request: Request,
        instance: FutureStrategyInstanceModel,
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
        query_db: AsyncSession = Depends(get_db),
):
    """
    更新策略实例
    """
    if not instance.id:
        logger.error('更新期货策略实例失败：实例ID不能为空')
        return ResponseUtil.failure(msg='实例ID不能为空')

    update_instance_result = await FutureStrategyInstanceService.update_strategy_instance_services(
        query_db, instance.id, instance
    )
    # 这里使用instance.instance获取实例名进行日志记录
    logger.info(
        f'用户{current_user.user.user_name}更新期货策略实例{instance.instance if instance.instance else instance.id}成功')

    return ResponseUtil.success(msg=update_instance_result.message)


@futureStrategyInstanceController.delete('', dependencies=[
    Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:delete'))])
@Log(title='期货策略实例管理', business_type=BusinessType.DELETE)
async def delete_future_strategy_instance(
        request: Request,
        delete_model: DeleteFutureStrategyInstanceModel,
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
        query_db: AsyncSession = Depends(get_db),
):
    """
    删除策略实例
    """
    delete_instance_result = await FutureStrategyInstanceService.delete_strategy_instance_services(
        query_db, delete_model
    )
    logger.info(f'用户{current_user.user.user_name}删除期货策略实例成功')

    return ResponseUtil.success(msg=delete_instance_result.message)


@futureStrategyInstanceController.post('/import', dependencies=[
    Depends(CheckUserInterfaceAuth('kylin:futureStrategyInstance:import'))])
@Log(title='期货策略实例管理', business_type=BusinessType.IMPORT)
async def import_future_strategy_instance(
        request: Request,
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
        query_db: AsyncSession = Depends(get_db),
):
    """
    导入策略实例（自动查找特定目录下的cta_strategy_setting.json文件）
    """
    import_instance_result = await FutureStrategyInstanceService.import_strategy_instance_services(
        query_db
    )
    logger.info(f'用户{current_user.user.user_name}导入期货策略实例成功')

    return ResponseUtil.success(msg=import_instance_result.message)
